{% extends "base.html" %}

{% block title %}依赖管理 - XbyJob{% endblock %}

{% block extra_css %}
<style>
    .package-card {
        transition: all 0.2s ease;
        border-left: 4px solid #e9ecef;
    }
    .package-card:hover {
        border-left-color: #007bff;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    .package-card.system-package {
        border-left-color: #6c757d;
        background-color: #f8f9fa;
    }
    .package-version {
        font-family: 'Monaco', 'Consolas', monospace;
        font-size: 0.9em;
        color: #6c757d;
    }
    .search-result-item {
        cursor: pointer;
        transition: background-color 0.2s;
    }
    .search-result-item:hover {
        background-color: #f8f9fa;
    }
    .system-package-badge {
        background-color: #6c757d !important;
    }
    .loading-spinner {
        display: none;
    }
    .package-actions {
        opacity: 0;
        transition: opacity 0.2s;
    }
    .package-card:hover .package-actions {
        opacity: 1;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-cubes me-2"></i>依赖管理</h2>
                <div class="btn-group">
                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#installModal">
                        <i class="fas fa-plus"></i> 安装包
                    </button>
                    <button type="button" class="btn btn-outline-secondary" onclick="refreshPackageList()">
                        <i class="fas fa-sync-alt"></i> 刷新
                    </button>
                    <button type="button" class="btn btn-outline-info" onclick="exportRequirements()">
                        <i class="fas fa-download"></i> 导出Requirements
                    </button>
                </div>
            </div>

            <!-- 搜索和过滤 -->
            <div class="row mb-4">
                <div class="col-md-6">
                    <div class="input-group">
                        <span class="input-group-text"><i class="fas fa-search"></i></span>
                        <input type="text" class="form-control" id="packageSearch" placeholder="搜索已安装的包...">
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="d-flex align-items-center">
                        <div class="form-check me-3">
                            <input class="form-check-input" type="checkbox" id="showSystemPackages" checked>
                            <label class="form-check-label" for="showSystemPackages">
                                显示系统包
                            </label>
                        </div>
                        <div class="text-muted">
                            共 <span id="packageCount">0</span> 个包
                        </div>
                    </div>
                </div>
            </div>

            <!-- 包列表 -->
            <div id="packageList" class="row">
                <div class="col-12 text-center py-5">
                    <div class="loading-spinner" style="display: block;">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2">正在加载包列表...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 安装包模态框 -->
<div class="modal fade" id="installModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">安装Python包</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-8">
                        <h6>手动安装</h6>
                        <div class="mb-3">
                            <label for="packageName" class="form-label">包名</label>
                            <input type="text" class="form-control" id="packageName" placeholder="例如: requests">
                        </div>
                        <div class="mb-3">
                            <label for="packageVersion" class="form-label">版本 (可选)</label>
                            <input type="text" class="form-control" id="packageVersion" placeholder="例如: 2.25.1">
                        </div>
                        <button type="button" class="btn btn-primary" id="installBtn">
                            <i class="fas fa-download"></i> 安装
                        </button>
                    </div>
                    <div class="col-md-4">
                        <h6>镜像源选择</h6>
                        <div class="mb-3">
                            <label for="mirrorSource" class="form-label">安装镜像源</label>
                            <select class="form-select" id="mirrorSource">
                                <option value="">默认官方源</option>
                                <option value="https://pypi.tuna.tsinghua.edu.cn/simple/">清华大学源</option>
                                <option value="https://mirrors.aliyun.com/pypi/simple/">阿里云源</option>
                                <option value="https://pypi.mirrors.ustc.edu.cn/simple/">中科大源</option>
                                <option value="https://pypi.douban.com/simple/">豆瓣源</option>
                                <option value="https://mirrors.163.com/pypi/simple/">网易源</option>
                            </select>
                            <div class="form-text">选择合适的镜像源可以加快包的下载速度</div>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="trustHost" checked>
                                <label class="form-check-label" for="trustHost">
                                    信任镜像源主机
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 卸载确认模态框 -->
<div class="modal fade" id="uninstallModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认卸载</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    您确定要卸载包 <strong id="uninstallPackageName"></strong> 吗？
                </div>
                <p class="text-muted">注意：只能卸载非系统依赖项的包，系统核心包无法卸载。</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmUninstallBtn">
                    <i class="fas fa-trash"></i> 确认卸载
                </button>
            </div>
        </div>
    </div>
</div>

{% endblock %}

{% block extra_js %}
<script>
let allPackages = [];
let currentUninstallPackage = null;
let isLoadingPackages = false; // 防止重复加载
let currentController = null; // 当前的AbortController
let requestAttempts = 0; // 请求尝试次数
let lastRequestTime = 0; // 上次请求时间

// 系统包列表（不允许卸载）
const systemPackages = [
    'pip', 'setuptools', 'wheel', 'python', 'distutils', 'importlib', 
    'pkg-resources', 'six', 'certifi', 'urllib3', 'chardet', 'idna',
    'flask', 'werkzeug', 'jinja2', 'markupsafe', 'itsdangerous', 'click'
];

$(document).ready(function() {
    console.log('Dependencies页面初始化');
    
    // 检查jQuery和全局函数
    console.log('jQuery版本:', $.fn.jquery);
    console.log('全局showMessage函数:', typeof window.showMessage);
    
    loadPackageList();
    
    // 搜索功能
    $('#packageSearch').on('input', function() {
        filterPackages();
    });
    
    // 系统包显示切换
    $('#showSystemPackages').on('change', function() {
        filterPackages();
    });
    
    // 添加安装按钮点击事件
    $('#installBtn').on('click', function(e) {
        console.log('安装按钮点击');
        e.preventDefault();
        installPackage();
    });
    
    // 添加卸载按钮点击事件（事件委托）
    $(document).on('click', '.uninstall-btn', function(e) {
        console.log('卸载按钮点击');
        e.preventDefault();
        const packageName = $(this).data('package');
        showUninstallModal(packageName);
    });
    
    // 添加确认卸载按钮点击事件
    $('#confirmUninstallBtn').on('click', function(e) {
        console.log('确认卸载按钮点击');
        e.preventDefault();
        confirmUninstall();
    });
    
    // 添加重试按钮点击事件（事件委托）
    $(document).on('click', '.retry-btn', function(e) {
        console.log('重试按钮点击');
        e.preventDefault();
        refreshPackageList();
    });
});

// 重置加载状态的全局函数
function resetLoadingState() {
    console.log('重置加载状态');
    isLoadingPackages = false;
    
    // 安全地取消当前请求
    if (currentController) {
        console.log('取消当前fetch请求');
        currentController.abort();
        currentController = null;
    }
    
    requestAttempts = 0;
    lastRequestTime = 0;
    $('#packageList').html('<div class="col-12 text-center py-5"><div class="text-muted"><i class="fas fa-box-open fa-3x mb-3"></i><p>点击重试按钮重新加载包列表</p></div></div>');
    showMessage('状态已重置，请点击重试按钮重新加载', 'info');
}

// 加载模拟数据的函数
function loadMockData() {
    console.log('手动加载模拟数据');
    isLoadingPackages = false;
    
    // 安全地取消当前请求
    if (currentController) {
        console.log('取消当前fetch请求');
        currentController.abort();
        currentController = null;
    }
    
    // 显示加载状态
    $('#packageList').html('<div class="col-12 text-center py-5"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div><p class="mt-2">正在加载模拟数据...</p></div>');
    
    setTimeout(() => {
        // 模拟数据
        const mockPackages = [
            { name: 'requests', version: '2.28.2', summary: 'Python HTTP for Humans', is_system: false },
            { name: 'numpy', version: '1.24.3', summary: '数值计算库', is_system: false },
            { name: 'pandas', version: '2.0.1', summary: '数据分析库', is_system: false },
            { name: 'matplotlib', version: '3.7.1', summary: '绘图库', is_system: false },
            { name: 'scikit-learn', version: '1.2.2', summary: '机器学习库', is_system: false },
            { name: 'flask', version: '2.3.2', summary: 'Web框架', is_system: true },
            { name: 'sqlalchemy', version: '2.0.15', summary: 'SQL工具包和ORM', is_system: true },
            { name: 'celery', version: '5.3.1', summary: '分布式任务队列', is_system: true },
            { name: 'redis', version: '4.5.5', summary: 'Redis客户端', is_system: true },
            { name: 'pymysql', version: '1.0.3', summary: 'MySQL客户端', is_system: true }
        ];
        
        allPackages = mockPackages;
        console.log('模拟包数量:', allPackages.length);
        
        displayPackages(allPackages);
        updatePackageCount();
        console.log('模拟包列表显示完成');
        
        showMessage('包列表加载成功（模拟数据）', 'info');
        
        // 添加提示信息
        $('#packageList').prepend(`
            <div class="col-12 mb-4">
                <div class="alert alert-warning">
                    <i class="fas fa-info-circle me-2"></i>
                    <strong>提示：</strong> 依赖管理API服务当前不可用，显示的是模拟数据。安装和卸载功能暂时无法使用。
                </div>
            </div>
        `);
        
        // 禁用安装和卸载按钮
        $('#installBtn').prop('disabled', true);
        $('.uninstall-btn').prop('disabled', true);
    }, 1000); // 模拟加载延迟
}

function loadPackageList() {
    const now = Date.now();
    requestAttempts++;
    
    console.log(`开始加载包列表 - 尝试次数: ${requestAttempts}, 上次请求间隔: ${lastRequestTime ? now - lastRequestTime : 0}ms`);
    
    if (isLoadingPackages) {
        console.log('正在加载包列表，忽略重复请求');
        return;
    }
    
    // 如果距离上次请求太近，延迟执行
    if (lastRequestTime && (now - lastRequestTime < 2000)) {
        console.log('距离上次请求太近，延迟2秒执行');
        setTimeout(() => loadPackageList(), 2000);
        return;
    }
    
    isLoadingPackages = true;
    lastRequestTime = now;
    
    // 取消之前的请求
    if (currentController) {
        console.log('取消之前的fetch请求');
        currentController.abort();
        currentController = null;
    }
    
    // 显示加载状态
    $('#packageList').html('<div class="col-12 text-center py-5"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">加载中...</span></div><p class="mt-2">正在加载包列表...</p></div>');
    
    // 创建AbortController用于取消请求
    currentController = new AbortController();
    
    // 尝试调用真实API
    fetch('/api/dependencies', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'Cache-Control': 'no-cache',
            'Request-ID': `${now}-${requestAttempts}`
        },
        signal: currentController.signal,
        credentials: 'same-origin',
        cache: 'no-cache'
    })
    .then(response => {
        console.log(`fetch响应收到 [${now}-${requestAttempts}]:`, response.status, response.statusText);
        console.log('响应URL:', response.url);
        
        // 检查是否被重定向到登录页面
        if (response.url.includes('/auth/login')) {
            throw new Error('需要重新登录');
        }
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        return response.json();
    })
    .then(response => {
        console.log(`SUCCESS回调被执行 [${now}-${requestAttempts}]！`);
        console.log('获取包列表响应:', response);
        
        if (response && response.success) {
                    allPackages = response.data || [];
            console.log('所有包数量:', allPackages.length);
            
            displayPackages(allPackages);
            updatePackageCount();
            console.log('包列表显示完成');
            
            showMessage('包列表加载成功', 'success');
            requestAttempts = 0; // 重置尝试次数
        } else {
            console.error('获取包列表失败:', response ? response.message : '未知错误');
            showMessage('获取包列表失败: ' + (response ? response.message : '未知错误'), 'danger');
        }
        
        isLoadingPackages = false;
    })
    .catch(error => {
        console.log(`加载包列表错误 [${now}-${requestAttempts}]:`, error);
        
        // 如果是AbortError，说明请求被取消
        if (error.name === 'AbortError') {
            console.log('请求被取消，忽略错误');
            return;
        }
        
        // 如果需要重新登录，重定向到登录页面
        if (error.message === '需要重新登录') {
            console.log('检测到需要重新登录，重定向到登录页面');
            window.location.href = '/auth/login?next=' + encodeURIComponent(window.location.pathname);
            return;
        }
        
        // API调用失败，使用模拟数据
        console.log('API调用失败，使用模拟数据:', error.message);
        
        setTimeout(() => {
            // 模拟数据
            const mockPackages = [
                { name: 'requests', version: '2.28.2', summary: 'Python HTTP for Humans', is_system: false },
                { name: 'numpy', version: '1.24.3', summary: '数值计算库', is_system: false },
                { name: 'pandas', version: '2.0.1', summary: '数据分析库', is_system: false },
                { name: 'matplotlib', version: '3.7.1', summary: '绘图库', is_system: false },
                { name: 'scikit-learn', version: '1.2.2', summary: '机器学习库', is_system: false },
                { name: 'flask', version: '2.3.2', summary: 'Web框架', is_system: true },
                { name: 'sqlalchemy', version: '2.0.15', summary: 'SQL工具包和ORM', is_system: true },
                { name: 'celery', version: '5.3.1', summary: '分布式任务队列', is_system: true },
                { name: 'redis', version: '4.5.5', summary: 'Redis客户端', is_system: true },
                { name: 'pymysql', version: '1.0.3', summary: 'MySQL客户端', is_system: true }
            ];
            
            allPackages = mockPackages;
            console.log('模拟包数量:', allPackages.length);
            
            displayPackages(allPackages);
            updatePackageCount();
            console.log('模拟包列表显示完成');
            
            showMessage('包列表加载成功（模拟数据）', 'info');
            
            // 添加提示信息
            $('#packageList').prepend(`
                <div class="col-12 mb-4">
                    <div class="alert alert-warning">
                        <i class="fas fa-info-circle me-2"></i>
                        <strong>提示：</strong> 依赖管理API服务当前不可用，显示的是模拟数据。安装和卸载功能暂时无法使用。
                    </div>
                </div>
            `);
            
            // 禁用安装和卸载按钮
            $('#installBtn').prop('disabled', true);
            $('.uninstall-btn').prop('disabled', true);
            
            isLoadingPackages = false;
        }, 1000); // 模拟加载延迟
    });
}

function displayPackages(packages) {
    const container = $('#packageList');
    
    if (packages.length === 0) {
        container.html(`
            <div class="col-12 text-center py-5">
                <div class="text-muted">
                    <i class="fas fa-box-open fa-3x mb-3"></i>
                    <p>没有找到相关的包</p>
                </div>
            </div>
        `);
        return;
    }
    
    let html = '';
    packages.forEach(function(pkg) {
        const isSystemPackage = systemPackages.includes(pkg.name.toLowerCase());
        const cardClass = isSystemPackage ? 'package-card system-package' : 'package-card';
        
        html += `
            <div class="col-md-6 col-lg-4 mb-3">
                <div class="card ${cardClass}">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <h6 class="card-title mb-1">
                                    ${pkg.name}
                                    ${isSystemPackage ? '<span class="badge bg-secondary system-package-badge ms-2">系统包</span>' : ''}
                                </h6>
                                <div class="package-version mb-2">v${pkg.version}</div>
                                ${pkg.summary ? `<p class="card-text text-muted small">${pkg.summary}</p>` : ''}
                            </div>
                            <div class="package-actions">
                                ${!isSystemPackage ? `
                                    <button class="btn btn-sm btn-outline-danger uninstall-btn" data-package="${pkg.name}" title="卸载">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    
    container.html(html);
}

function filterPackages() {
    const query = $('#packageSearch').val().toLowerCase();
    const showSystem = $('#showSystemPackages').is(':checked');
    
    let filtered = allPackages.filter(function(pkg) {
        const matchesQuery = pkg.name.toLowerCase().includes(query) || 
                           (pkg.summary && pkg.summary.toLowerCase().includes(query));
        
        if (!showSystem) {
            const isSystemPackage = systemPackages.includes(pkg.name.toLowerCase());
            return matchesQuery && !isSystemPackage;
        }
        
        return matchesQuery;
    });
    
    displayPackages(filtered);
    updatePackageCount(filtered.length);
}

function updatePackageCount(count) {
    if (count === undefined) {
        count = allPackages.length;
    }
    $('#packageCount').text(count);
}

function refreshPackageList() {
    console.log('刷新包列表被调用，当前isLoadingPackages:', isLoadingPackages);
    
    if (isLoadingPackages) {
        console.log('正在加载包列表，忽略刷新请求');
        return;
    }
    
    console.log('开始刷新包列表...');
    loadPackageList();
}

function installPackage() {
    console.log('installPackage函数被调用');
    
    const packageName = $('#packageName').val().trim();
    const packageVersion = $('#packageVersion').val().trim();
    const mirrorSource = $('#mirrorSource').val();
    const trustHost = $('#trustHost').is(':checked');
    
    console.log('输入值:', {
        packageName: packageName,
        packageVersion: packageVersion,
        mirrorSource: mirrorSource,
        trustHost: trustHost
    });
    
    if (!packageName) {
        console.log('包名为空，显示警告');
        showMessage('请输入包名', 'warning');
        return;
    }
    
    const packageSpec = packageVersion ? `${packageName}==${packageVersion}` : packageName;
    console.log('包规格:', packageSpec);
    
    // 构建请求数据
    const requestData = {
        package: packageSpec
    };
    
    // 如果选择了镜像源，添加到请求中
    if (mirrorSource) {
        requestData.index_url = mirrorSource;
        requestData.trusted_host = trustHost;
    }
    
    console.log('发送请求数据:', requestData);
    
    // 显示加载状态
    const installBtn = $('#installBtn');
    const originalText = installBtn.html();
    installBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 安装中...');
    
    // 设置超时恢复按钮状态（防止按钮永远禁用）
    const timeoutId = setTimeout(function() {
        console.log('请求超时，恢复按钮状态');
        installBtn.prop('disabled', false).html(originalText);
        showMessage('请求超时，请重试', 'warning');
    }, 60000); // 60秒超时
    
    $.ajax({
        url: '/api/dependencies/install',
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(requestData),
        timeout: 60000, // 设置AJAX超时时间
        success: function(response) {
            console.log('安装成功响应:', response);
            clearTimeout(timeoutId); // 清除超时定时器
            
            if (response.success) {
                showMessage('包安装成功', 'success');
                $('#installModal').modal('hide');
                
                // 强制清除可能残留的模态框背景遮罩
                setTimeout(function() {
                    $('.modal-backdrop').remove();
                    $('body').removeClass('modal-open');
                    $('body').css('padding-right', '');
                }, 300);
                
                $('#packageName').val('');
                $('#packageVersion').val('');
                $('#mirrorSource').val('');
                $('#trustHost').prop('checked', true);
                
                // 检查是否正在加载，避免重复刷新
                if (!isLoadingPackages) {
                    console.log('安装成功，开始刷新包列表');
                    refreshPackageList();
                } else {
                    console.log('安装成功，但正在加载包列表，跳过刷新');
                }
            } else {
                showMessage('安装失败: ' + (response.message || '未知错误'), 'danger');
            }
        },
        error: function(xhr, status, error) {
            console.log('安装失败:', { xhr: xhr, status: status, error: error });
            clearTimeout(timeoutId); // 清除超时定时器
            
            // 检查是否需要重新登录
            if (xhr.status === 302 || (xhr.responseText && xhr.responseText.includes('/auth/login'))) {
                console.log('检测到需要重新登录，重定向到登录页面');
                window.location.href = '/auth/login?next=' + encodeURIComponent(window.location.pathname);
                return;
            }
            
            let message = '安装失败';
            if (status === 'timeout') {
                message = '请求超时，请检查网络连接';
            } else if (xhr.responseJSON && xhr.responseJSON.message) {
                message = xhr.responseJSON.message;
            } else if (xhr.responseText) {
                try {
                    const errorData = JSON.parse(xhr.responseText);
                    message = errorData.message || '安装失败';
                } catch (e) {
                    message = '网络错误，请检查连接';
                }
            } else if (xhr.status === 0) {
                message = '无法连接到服务器，请检查网络';
            } else {
                message = `HTTP错误 ${xhr.status}: ${error || '未知错误'}`;
            }
            showMessage(message, 'danger');
        },
        complete: function(xhr, status) {
            console.log('请求完成:', { status: status, readyState: xhr.readyState });
            clearTimeout(timeoutId); // 确保清除超时定时器
            
            // 无论成功失败都恢复按钮状态
            installBtn.prop('disabled', false).html(originalText);
            
            // 如果是成功完成，额外等待一下再恢复按钮
            if (status === 'success') {
                setTimeout(function() {
                    installBtn.prop('disabled', false).html(originalText);
                }, 100);
            }
        }
    });
}

function showUninstallModal(packageName) {
    currentUninstallPackage = packageName;
    $('#uninstallPackageName').text(packageName);
    $('#uninstallModal').modal('show');
}

function confirmUninstall() {
    if (!currentUninstallPackage) {
        console.log('没有当前卸载包，返回');
        return;
    }
    
    console.log('开始卸载包:', currentUninstallPackage);
    
    // 显示卸载中状态
    const confirmBtn = $('#confirmUninstallBtn');
    const originalText = confirmBtn.html();
    console.log('按钮原始文本:', originalText);
    
    confirmBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 卸载中...');
    console.log('按钮状态已更新为卸载中');
    
    // 设置超时恢复按钮状态
    const timeoutId = setTimeout(function() {
        console.log('卸载请求超时，恢复按钮状态');
        confirmBtn.prop('disabled', false).html(originalText);
        showMessage('卸载请求超时，请重试', 'warning');
    }, 30000); // 30秒超时
    
    const apiUrl = `/api/dependencies/${currentUninstallPackage}`;
    console.log('发送卸载请求到:', apiUrl);
    
    $.ajax({
        url: apiUrl,
        method: 'DELETE',
        timeout: 30000, // 设置AJAX超时时间
        beforeSend: function(xhr) {
            console.log('即将发送请求:', xhr);
        },
        success: function(response) {
            console.log('卸载成功响应:', response);
            clearTimeout(timeoutId);
            
            if (response.success) {
                showMessage('包卸载成功', 'success');
                $('#uninstallModal').modal('hide');
                
                // 检查是否正在加载，避免重复刷新
                if (!isLoadingPackages) {
                    console.log('卸载成功，开始刷新包列表');
                    refreshPackageList();
                } else {
                    console.log('卸载成功，但正在加载包列表，跳过刷新');
                }
            } else {
                showMessage('卸载失败: ' + response.message, 'danger');
            }
        },
        error: function(xhr, status, error) {
            console.log('卸载失败:', { xhr: xhr, status: status, error: error });
            console.log('响应状态:', xhr.status);
            console.log('响应文本:', xhr.responseText);
            clearTimeout(timeoutId);
            
            // 检查是否需要重新登录
            if (xhr.status === 302 || (xhr.responseText && xhr.responseText.includes('/auth/login'))) {
                console.log('检测到需要重新登录，重定向到登录页面');
                window.location.href = '/auth/login?next=' + encodeURIComponent(window.location.pathname);
                return;
            }
            
            let message = '卸载失败';
            if (status === 'timeout') {
                message = '卸载请求超时，请检查网络连接';
            } else if (xhr.responseJSON && xhr.responseJSON.message) {
                message = xhr.responseJSON.message;
            } else if (xhr.responseText) {
                try {
                    const errorData = JSON.parse(xhr.responseText);
                    message = errorData.message || '卸载失败';
                } catch (e) {
                    message = '网络错误，请检查连接';
                }
            } else if (xhr.status === 0) {
                message = '无法连接到服务器，请检查网络';
            } else {
                message = `HTTP错误 ${xhr.status}: ${error || '未知错误'}`;
            }
            showMessage(message, 'danger');
        },
        complete: function(xhr, status) {
            console.log('卸载请求完成:', { status: status, readyState: xhr.readyState });
            clearTimeout(timeoutId);
            
            // 恢复按钮状态
            confirmBtn.prop('disabled', false).html(originalText);
            currentUninstallPackage = null;
            console.log('按钮状态已恢复，当前卸载包已清空');
        }
    });
}

function exportRequirements() {
    window.open('/api/dependencies/export', '_blank');
}

function showMessage(message, type) {
    console.log('显示消息:', message, type);
    // 使用全局toast通知功能
    if (window.showToast && typeof window.showToast === 'function') {
        window.showToast(message, type, 3000);
    } else if (window.parent && window.parent.showMessage && typeof window.parent.showMessage === 'function') {
        window.parent.showMessage(message, type, 3000);
    } else {
        console.error('全局showMessage函数不可用，使用alert代替');
        alert(message);
    }
}
</script>
{% endblock %}